const EndlessGameModel = require('./../model/EndlessGameModel');
let Gcommon = require('../model/Common');

// 媒体音乐资源tep
// var audioTep = cc.Class({
//   name: 'audioTep',
//   properties: {
//     type: cc.AudioClip,
//     default: null
//   }
// });

cc.Class({
  extends: cc.Component,
  properties: {
    BlockList: require('BlockList'), //砖块的预制体
    GameOverPopue: cc.Prefab,
    // 游戏场景
    Content: {
      default: null,
      type: cc.Node
    },
    // 轨迹条
    ballLink: {
      default: null,
      type: cc.Sprite
    },
    // // npc 球体
    // Npc: {
    //   default: null,
    //   type: cc.Sprite
    // },
    // npc 预制体容器
    NpcPrefabContainer: {
      default: null,
      type: cc.Node
    },
    // npc 球体 预制体
    NpcPrefab: {
      default: null,
      type: cc.Prefab
    },
    audioBall1: {
      type: cc.AudioClip,
      default: null
    },
    audioBlock: {
      type: cc.AudioClip,
      default: null
    },
    audioBuff1: {
      type: cc.AudioClip,
      default: null
    },
    dig_ui: {
      type: cc.Prefab,
      default: null
    },
    warnLine: {
      type: cc.Node,
      default: null
    }
  },

  onLoad: function() {
    // 开启物理
    cc.director.getPhysicsManager().enabled = true;
    // 开启碰撞
    cc.director.getCollisionManager().enabled = true;

    // 记录下线的y轴
    this.ballLink_y = this.ballLink.node.y;

    this.EndlessGameModel = new EndlessGameModel();

    this.node.on(
      cc.Node.EventType.TOUCH_START,
      function(event) {
        this.touchStart(event);
      }.bind(this),
      this
    );

    this.node.on(
      cc.Node.EventType.TOUCH_MOVE,
      function(event) {
        this.touchMove(event);
      }.bind(this),
      this
    );

    this.node.on(
      cc.Node.EventType.TOUCH_END,
      function(event) {
        this.touchEnd(event);
      }.bind(this),
      this
    );
    this.BlockList.init(this);
  },

  update(dt) {
    if (this.EndlessGameModel.isMoveDown) {
      // 触发砖块下移动作并更改状态
      this.EndlessGameModel.isMoveDown = false;
      this.initBlock();
    }
  },

  init() {
    // this.physicsManager.enabled = true;
    this.EndlessGameModel.init();
    this.NpcPrefabContainer.destroyAllChildren();
    // 这里需要清空下砖块
    let index = this.Content.children.findIndex(function(obj, index, objs) {
      return obj._name === 'BlockScreen';
    });
    this.Content.children[index].destroyAllChildren();
    this.BlockList.init(this);

    // this.gameView.init(this);
    // // this.ball.init(this);
    // this.paddle.init(this);
    // this.brickLayout.init(this.gameModel.bricksNumber);
    // this.onAddBallNFC(1);
  },

  // 砖块的下移&添加
  initBlock() {
    let index = this.Content.children.findIndex(function(obj, index, objs) {
      return obj._name === 'BlockScreen';
    });
    // console.log(this.Content.children[index].children)

    let isWaring = false;
    let maxHeight =
      -this.Content.maxHeight +
      (this.EndlessGameModel.BlockWidth + this.EndlessGameModel.BlockSpacing);

    // 先预判下最后一层是和底部边线的距离
    // console.log(
    //   this.Content.children[index],
    //   this.Content.children[index].children[1].y
    //   // this.Content.children[index].children[
    //   //   this.Content.children[index].children.length - 1
    //   // ].y
    // );

    this.warnLine.active = false;
    if (
      this.Content.children[index].height +
        this.Content.children[index].children[1].y <
      0
    ) {
      this.stopGame();
      return;
    }
    if (
      this.Content.children[index].height +
        this.Content.children[index].children[1].y >
        50 &&
      this.Content.children[index].height +
        this.Content.children[index].children[1].y <=
        200
    ) {
      // 到了警戒点
      this.warnLine.active = true;
    }

    // 下移并初始化第一行
    this.Content.children[index].children.forEach(ele => {
      ele.y =
        ele.y -
        (this.EndlessGameModel.BlockWidth + this.EndlessGameModel.BlockSpacing);
    });
    // 初始化第一行
    this.BlockList.init(this);
    // console.log(this.BlockList);
  },

  // 弹射线 触摸事件
  touchStart: function(event) {
    if (!this.EndlessGameModel.isActive) {
      // console.log('touchstart');
      this.ballLink.enabled = true;
      this.ballLink.node.setPosition(
        cc.v2(this.EndlessGameModel.LastNpcPositionX, this.ballLink_y)
      );
    }
  },
  touchMove: function(event) {
    if (!this.EndlessGameModel.isActive) {
      // console.log('touchmove');
      var touchX = event.touch._point.x;
      this.ballLink.node.setRotation(touchX);

      if (this.ballLink.node.rotation < 280) {
        this.ballLink.node.setRotation(280);
      }
      if (this.ballLink.node.rotation > 440) {
        this.ballLink.node.setRotation(440);
      }
    }
  },

  touchEnd: function(event) {
    if (!this.EndlessGameModel.isActive && this.EndlessGameModel.isGame) {
      // console.log('touchend');
      this.EndlessGameModel.isActive = true;
      this.ballLink.enabled = false;

      // this.Npc.node.setPosition(cc.v2(0, -350));
      // var boxRigidBody = this.Npc.node.getComponent(cc.RigidBody);
      // var angle = -this.ballLink.node.rotation - 270;
      // var toX = Math.cos(angle * 0.017453293) * 100;
      // var toY = Math.sin(angle * 0.017453293) * 100;
      // boxRigidBody.linearVelocity = cc.v2(toX * 12, toY * 12);

      // if (this.isActivity == false) {
      // if (this.isBegin == false) {
      //   this.isBegin = true;
      // }

      this.schedule(
        function() {
          var boll = cc.instantiate(this.NpcPrefab);
          boll.getComponent('Npc').init(this);

          this.NpcPrefabContainer.addChild(boll);
          boll.setPosition(
            cc.v2(this.EndlessGameModel.LastNpcPositionX, this.ballLink_y)
          );
          // boll.x = this.EndlessGameModel.LastNpcPositionX;
          // boll.y = -465

          var boxRigidBody = boll.getComponent(cc.RigidBody);
          var angle = -this.ballLink.node.rotation - 270;
          var toX = Math.cos(angle * 0.017453293) * 100;
          var toY = Math.sin(angle * 0.017453293) * 100;
          boxRigidBody.linearVelocity = cc.v2(toX * 10, toY * 10);
        }.bind(this),
        0.08,
        this.EndlessGameModel.NpcBall - 1
      );

      // this.schedule(
      //   function() {
      //     this.indexBoll.enabled = false;
      //     this.isFirstBoll = false;
      //   }.bind(this),
      //   0.08 * (this.allBolls - 1),
      //   1
      // );

      // this.isActivity = true;
    }
  },

  // 媒体音乐播放迎请
  playSound(music) {
    // 游戏音效
    if (Gcommon.musicEffect) {
      cc.audioEngine.playEffect(music, false);
    }
  },

  // 碰撞到砖块
  onNpcBallContactBlock(ballNode, brickNode) {
    // buff
    if (brickNode.block_type === 'buff_1') {
      this.onBuffbom(brickNode);
      return;
    }

    // this.playSound(this.scoreAudio);
    // this.gameModel.addScore(1);
    this.EndlessGameModel.addScore(10);
    // this.gameView.updateScore(this.gameModel.score);

    let brickNodeHP = brickNode.children[1].getComponent(cc.Label).string;
    let bombAni = brickNode.children[0].getComponent(cc.Animation);

    this.playSound(this.audioBlock);
    if (brickNodeHP <= 1) {
      // 生命值小于1的时候执行动画并销毁最后判断是否结束游戏
      // bombAni.play('brick_burst');
      // bombAni.on(
      //   'stop',
      //   function() {
      brickNode.destroy(); // 前者是官方推荐方法 brickNode.parent = null;
      //     if (this.gameModel.bricksNumber <= 0) {
      //       this.stopGame();
      //     }
      //   },
      //   this
      // );
    } else {
      brickNode.children[1].getComponent(cc.Label).string = brickNodeHP -= 1;
    }
  },

  onBuffbom(block) {
    //buff 效果
    // console.log('buff效果');
    this.playSound(this.audioBuff1);
    this.EndlessGameModel.NpcBall++;
    this.EndlessGameModel.NpcBallSign++; //这里自增是为了兼容footer.js中逻辑判断的兼容
    block.destroy();
    // console.log(block.children[1].getComponent(cc.Label).string);
  },

  // 碰撞到边界
  onNpcBallContactBorder(self, other) {
    this.playSound(this.audioBall1);
  },

  onPause() {
    console.log(this.node);
    // cc.director.getPhysicsManager().enabled = false;
    var _directorGame = cc.director.getPhysicsManager();
    _directorGame.enabled = false;

    var dig_ui = cc.instantiate(this.dig_ui);
    this.node.addChild(dig_ui);
    dig_ui.getComponent('popue_dig').show_dlg({
      hide: () => {
        _directorGame.enabled = true;
        // cc.director.getPhysicsManager().enabled = true;
        // dig_ui.destroy();
        // cc.director.pause();
        // cc.director.resume();
      },
      restart: () => {
        this.init();
      }
    });
  },

  stopGame() {
    //游戏结束
    this.EndlessGameModel.isGame = false;
    let GameOverPopue = cc.instantiate(this.GameOverPopue);
    this.node.addChild(GameOverPopue);
    GameOverPopue.getComponent('game_over_dig').show_dlg({
      restart: () => {
        this.init();
      },
      score: this.EndlessGameModel.score
    });
  },

  test() {
    cc.director.loadScene('home');
  }
});
